import { NextPage } from "next";
import { useState } from "react";
import { BusinessItemInfo } from "../types/business";
import { useQuery } from "@tanstack/react-query";
import SearchPage from "../components/SearchPage";
import {
  Cascader,
  Form,
  Input,
  Select,
  Row,
  Col,
  Card,
  Tag,
  Button,
  Checkbox,
  Popconfirm,
  message,
} from "antd";
import { ContextVal } from "../components/SearchPage/context";
import { getPatternList } from "./parseTask";
import { useRouter } from "next/router";
import request from "../utils/request";
import { find, forEach, isArray, map } from "lodash";
import Dialog from "../components/Dialog";
import CaptchInfo from "../components/CaptchInfo";
import MeidaCore from "../components/MeidaCore";
import { downloadLink } from "../utils/download";
import { DeleteOutlined } from "@ant-design/icons";
import LoadBtn from "../components/LoadBtn";

let pageCore: ContextVal;

const ParseTaskDetail: NextPage = () => {
  const { query } = useRouter();
  const [selected, setSelected] = useState<Set<any>>(new Set());
  const task_id = query.id

  const [list, setList] = useState<BusinessItemInfo[]>([]);
  const { data: taskOptions = [] } = useQuery({
    queryKey: ["taskOptions", task_id],
    queryFn: async () => {
      const data = await request("/task/getPatternList", {
        params: {
          task_id
        }
      });
      return map(data, (item) => ({
        key: item.id,
        label: item.title,
      }));
    },
  });
  const { data: fileOptions = [] } = useQuery({
    queryKey: ["fileOptions"],
    queryFn: async () => {
      const data = await request("/task/getFileTypeList", {
        params: {
          task_id
        }
      });
      return map(data, (item) => ({
        key: item.id,
        label: item.title,
      }));
    },
  });
  const { data: elementOptions = [] } = useQuery({
    queryKey: ["elementOptions"],
    queryFn: async () => {
      const data = await request("/pattern/info/element/list", {
        params: {
          task_id
        }
      });
      return map(data, (group) => ({
        value: group.id,
        label: group.title,
        children: map(group.sub_tag_list, (item) => ({
          value: item.id,
          label: item.title,
        })),
      }));
    },
  });
  const onShowDetail = async (id) => {
    Dialog({
      title: "模型分析",
      width: 1200,
      hideConfirm: true,
      content: <CaptchInfo id={id} />,
    });
  };
  return (
    <SearchPage
      src="/task/media/page"
      defaultFilters={{ task_id: query.id }}
      uploadData={(list) => {
        setList(list);
        setSelected(new Set());
      }}
      pageSizeOptions={[12,24,48]}
      searchFormat={(data) => {
        const searchElementList = [];
        forEach(data.element_list, (arr) => {
          if (!isArray(arr)) return;
          if (arr.length === 2) {
            searchElementList.push(arr[1]);
          }
          let item = find(elementOptions, { value: arr[0] });
          if (arr.length === 1 && item) {
            forEach(item?.children, (it) => {
              searchElementList.push(it.value);
            });
          }
        });
        data.element_list = searchElementList;
        return data;
      }}
      breadcrumbList={[
        {
          href: "/parseTask",
          label: "解析任务管理",
        },
        {
          href: `/parseTaskDetail?id=${query.id}`,
          label: "解析任务管理详情",
        },
      ]}
      onMount={(v) => (pageCore = v)}
    >
      <SearchPage.Search
        actions={[
          <Button
            type="primary"
            size="small"
            onClick={async () => {
              setSelected(new Set(list.map((item) => item.media_id)));
            }}
          >
            全选
          </Button>,
          <LoadBtn
            type="primary"
            size="small"
            onClick={async () => {
              const { url } = await request.post("/task/downloadMedia", {
                media_id: [...selected],
              });
              downloadLink(url);
            }}
          >
            下载选中
          </LoadBtn>,
          <LoadBtn
            type="primary"
            size="small"
            onClick={async () => {
              const media_id = await request.post(
                "/task/media/getMediaList",
                pageCore?.getSearchFilter?.()
              );
              const { url } = await request.post("/task/downloadMedia", {
                media_id,
              });
              downloadLink(url);
            }}
          >
            下载全部
          </LoadBtn>,
        ]}
      >
        <Form.Item noStyle>
          {({ getFieldValue }) => {
            setSearchTaskId(() => {
              return getFieldValue('task_id')
            })
            return null;
          }}
        </Form.Item>
        <Form.Item label="业务模型" name="pattern_info">
          <Select
            mode="multiple"
            style={{ width: 200 }}
            placeholder="请选择数据类型"
          >
            {map(taskOptions, (item) => (
              <Select.Option key={item.key}>{item.label}</Select.Option>
            ))}
          </Select>
        </Form.Item>
        <Form.Item label="数据类型" name="media_type_list">
          <Select
            style={{ width: 200 }}
            placeholder="请选择业务模型"
            mode="multiple"
            maxTagCount="responsive"
          >
            {map(fileOptions, (item) => (
              <Select.Option key={item.key}>{item.label}</Select.Option>
            ))}
          </Select>
        </Form.Item>
        <Form.Item label="命中元素" name="element_list">
          <Cascader
            multiple
            options={elementOptions}
            maxTagCount="responsive"
            style={{ width: 200 }}
            placeholder="请选择命中元素"
          />
        </Form.Item>
        <Form.Item label="关键词搜索" name="keyword">
          <Input placeholder="请输入关键词搜索" />
        </Form.Item>
      </SearchPage.Search>
      <SearchPage.Cont>
        <div className="p-[15px]">
          <Row
            gutter={[12, 12]}
            style={{ width: (350 + 12 * 2) * 4, margin: "auto" }}
          >
            {list.map((item) => (
              <Col>
                <Card
                  hoverable
                  style={{ width: 350, cursor: "pointer" }}
                  cover={(() => {
                    if (item.media_type === "video") {
                      return (
                        <div
                          onClick={(e) => {
                            e.stopPropagation();
                          }}
                          className="pointer-events-none"
                        >
                          <MeidaCore
                            source={item.cover_url}
                            type="video"
                            pointList={[]}
                            width={350}
                            height={300}
                          />
                        </div>
                      );
                    }
                    return (
                      <img
                        style={{ width: 350, height: 300, objectFit: "cover" }}
                        src={item.cover_url}
                      />
                    );
                  })()}
                  onClick={() => {
                    onShowDetail(item.media_id);
                  }}
                  bodyStyle={{
                    padding: 5,
                    paddingLeft: 5,
                    height: 50,
                    display: "flex",
                    alignItems: "center",
                  }}
                >
                  <div className="flex flex-none">
                    <div
                      className="mr-[5px] inline-block"
                      onClick={(e) => {
                        e.preventDefault();
                        e.stopPropagation();
                        selected.has(item.media_id)
                          ? selected.delete(item.media_id)
                          : selected.add(item.media_id);
                        setSelected(new Set(selected));
                      }}
                    >
                      <Checkbox checked={selected.has(item.media_id)} />
                    </div>
                    <div
                      className="inline-block"
                      onClick={(e) => {
                        e.stopPropagation();
                      }}
                    >
                      <Popconfirm
                        title="删除"
                        onConfirm={async () => {
                          await request.delete(`/task/media/${item.media_id}`);
                          message.success("删除成功");
                          pageCore.query?.mutate(null);
                        }}
                        okText="确定"
                        cancelText="取消"
                      >
                        <DeleteOutlined />
                      </Popconfirm>
                    </div>
                  </div>
                    {!item.is_hit && (
                      <div className="flex items-center justify-center flex-1">
                        正常
                      </div>
                    )}
                  {item.is_hit && (
                    <div className="flex flex-wrap pl-[5px] overflow-y-auto max-h-full flex-1 justify-center">
                      {map(item.pattern_info, (v) => (
                        <Tag className="m-[2px]">
                          {v?.pattern_name}({v?.hit_score}/{v?.total_score})
                        </Tag>
                      ))}
                    </div>
                  )}
                </Card>
              </Col>
            ))}
          </Row>
        </div>
      </SearchPage.Cont>
    </SearchPage>
  );
};

export default ParseTaskDetail;
